package com.da.javatest.webflux.handler;

import com.da.javatest.webflux.entity.User;
import com.da.javatest.webflux.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author JokerDa.
 * @date 2021/1/6 16:14
 * Description:
 */
public class UserHandler {

    private final UserService userService;

    public UserHandler(UserService userService) {
        this.userService = userService;
    }

    // 根据ID查询用户
    public Mono<ServerResponse> getUserById(ServerRequest request) {
        // 获取Id
        int id = Integer.parseInt(request.pathVariable("id"));
        // 调用service得到数据
        Mono<User> userMono = userService.getUserById(id);
        // 转换结果
        //return userMono.flatMap(
        //    user -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(fromObject(user)))
        //    .switchIfEmpty(ServerResponse.notFound().build());
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(userMono, User.class);
    }

    // 查询所有用户
    public Mono<ServerResponse> getAllUser(ServerRequest request) {
        Flux<User> users = userService.getAllUser();
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(users, User.class);
    }

    // 保存用户
    public Mono<ServerResponse> saveUser(ServerRequest request) {
        Mono<User> userMono = request.bodyToMono(User.class);
        return ServerResponse.ok().build(userService.saveUser(userMono));
    }

}
